package com.pan.kang.framework;


import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DynamicValueObject implements IDynamicModel {

    public DynamicAttributeMap valueMap = new DynamicAttributeMap();

    public DynamicValueObject() {
    }

    @Override
    public <T> T get(String name) {
        return (T) this.valueMap.get(name);
    }

    @Override
    public <T> void set(String name, T value) {
        setAttribute(this, name, value);
    }

    public static void setAttribute(IDynamicModel obj, String name, Object value) {
        PropertyDescriptor pd = getPropertyDescriptor(obj, name);
        if (pd != null) {
            Method md = pd.getWriteMethod();
            try {
                md.invoke(obj, value);
            } catch (Exception var7) {
                throw new RuntimeException(var7);
            }
        } else if (obj instanceof IDynamicModel) {
            setDynamicAttribute(obj, name, value);
        }
    }

    public static void setDynamicAttribute(IDynamicModel obj, String name, Object value) {
        DynamicAttributeMap map = null;
        if (obj instanceof DynamicValueObject) {
            map = getValueMap((DynamicValueObject) obj);
        }
        map.put(name, value);
    }

    static DynamicAttributeMap getValueMap(DynamicValueObject object) {
        DynamicAttributeMap map = object.valueMap;
        if (map == null) {
            map = new DynamicAttributeMap();
            object.valueMap = map;
        }
        return map;
    }

    public static PropertyDescriptor getPropertyDescriptor(Object instance, String name) {
        Map map = getInstancePropertyMap(instance.getClass());
        return (PropertyDescriptor) map.get(name);
    }

    public static Map getInstancePropertyMap(Class cls) {
        try {
            Map attrsMap = new ConcurrentHashMap();
            BeanInfo bi = Introspector.getBeanInfo(cls);
            PropertyDescriptor[] ps = bi.getPropertyDescriptors();
            PropertyDescriptor pd;
            for (int i = 0; i < ps.length; ++i) {
                pd = ps[i];
                attrsMap.put(pd.getName(), pd);
            }
            return attrsMap;
        } catch (IntrospectionException var8) {
            throw new RuntimeException(var8);
        }
    }
}
